document.addEventListener('DOMContentLoaded', async () => {
    // 使用let声明可重新赋值的变量
    let editUserForm = document.getElementById('editUserForm');
    const MINIO_BUCKET = 'http://192.168.88.77:9001/interview-bucket';

    // 加载用户信息到表单
    async function loadUserInfo() {
        try {
            // 显示加载状态
            const formContainer = editUserForm.parentElement;
            formContainer.innerHTML = `
                <div class="flex flex-col items-center py-10">
                    <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                    <p class="text-neutral-500">正在加载用户信息...</p>
                </div>
            `;

            const response = await fetch('/user/userInfo', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await response.json();
            if (data.code === 200) {
                const user = data.data;

                // 恢复表单显示
                formContainer.innerHTML = editUserForm.outerHTML;
                // 重新获取表单元素引用
                editUserForm = document.getElementById('editUserForm');

                // 填充表单数据
                document.getElementById('username').value = user.username;
                document.getElementById('nickName').value = user.nickName;
                document.getElementById('phone').value = user.phone;
                document.getElementById('email').value = user.email;
                document.getElementById('gender').value = user.gender.toString();
                document.getElementById('age').value = user.age;
                document.getElementById('jobInterest').value = user.jobInterest;
                document.getElementById('techTack').value = user.techTack;

                // 重新绑定表单提交事件
                bindFormSubmit();
            } else if (data.code === 401) {
                await Swal.fire({
                    icon: 'warning',
                    title: '登录状态失效',
                    text: '请重新登录以访问该页面',
                    confirmButtonText: '前往登录',
                    background: '#fef4f4',
                    iconColor: '#FF4444',
                    color: '#606266',
                });
                window.location.href = '/view/login.html';
            } else {
                formContainer.innerHTML = `
                    <div class="flex flex-col items-center py-10">
                        <div class="w-16 h-16 rounded-full bg-danger/10 flex items-center justify-center mb-4">
                            <i class="fa fa-exclamation-triangle text-danger text-2xl"></i>
                        </div>
                        <p class="text-neutral-700">${data.message || '获取用户信息失败'}</p>
                        <button onclick="loadUserInfo()" class="mt-4 bg-neutral-200 hover:bg-neutral-300 text-neutral-700 font-medium py-2 px-4 rounded-lg transition-colors">
                            重试
                        </button>
                    </div>
                `;
            }
        } catch (error) {
            console.error('加载用户信息失败:', error);
            const formContainer = editUserForm.parentElement;
            formContainer.innerHTML = `
                <div class="flex flex-col items-center py-10">
                    <div class="w-16 h-16 rounded-full bg-neutral-200 flex items-center justify-center mb-4">
                        <i class="fa fa-wifi text-neutral-500 text-2xl"></i>
                    </div>
                    <p class="text-neutral-700">网络连接错误，请重试</p>
                    <button onclick="loadUserInfo()" class="mt-4 bg-neutral-200 hover:bg-neutral-300 text-neutral-700 font-medium py-2 px-4 rounded-lg transition-colors">
                        重试
                    </button>
                </div>
            `;
        }
    }

    // 提交表单
    function bindFormSubmit() {
        // 移除之前的事件监听器
        if (editUserForm) {
            const newForm = editUserForm.cloneNode(true);
            editUserForm.parentNode.replaceChild(newForm, editUserForm);
            editUserForm = newForm;

            editUserForm.addEventListener('submit', async (e) => {
                e.preventDefault();

                const formData = {
                    username: document.getElementById('username').value,
                    nickName: document.getElementById('nickName').value,
                    phone: document.getElementById('phone').value,
                    email: document.getElementById('email').value,
                    gender: parseInt(document.getElementById('gender').value),
                    age: parseInt(document.getElementById('age').value),
                    jobInterest: document.getElementById('jobInterest').value,
                    techTack: document.getElementById('techTack').value
                };

                try {
                    // 显示加载状态
                    const submitButton = editUserForm.querySelector('button[type="submit"]');
                    const originalText = submitButton.innerHTML;
                    submitButton.disabled = true;
                    submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

                    const response = await fetch('/user/editUserInfo', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    });

                    const data = await response.json();
                    if (data.code === 200) {
                        await Swal.fire({
                            icon: 'success',
                            title: '保存成功',
                            text: '用户信息已更新',
                            background: '#f0f9eb',
                            iconColor: '#52c41a',
                            color: '#606266',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        window.location.href = 'userInfo.html';
                    } else {
                        await Swal.fire({
                            icon: 'error',
                            title: '保存失败',
                            text: data.message || '保存用户信息失败',
                            background: '#fef0f0',
                            iconColor: '#ff4d4f',
                            color: '#606266'
                        });
                    }
                } catch (error) {
                    console.error('提交表单失败:', error);
                    await Swal.fire({
                        icon: 'error',
                        title: '网络连接错误',
                        text: '请重试',
                        background: '#fef0f0',
                        iconColor: '#ff4d4f',
                        color: '#606266'
                    });
                } finally {
                    // 恢复按钮状态
                    const submitButton = editUserForm.querySelector('button[type="submit"]');
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalText;
                }
            });
        }
    }

    // 初始加载
    loadUserInfo();
    // 初始绑定表单提交事件
    bindFormSubmit();
});